package br.com.buildup.cripto;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import sun.misc.BASE64Encoder;

public abstract class CryptographyGeneric {
    
    private MessageDigest digest;
    private BASE64Encoder encoder;
    
    protected void useAlgorithm( String algorithm) throws NoSuchAlgorithmException{
        if ( digest == null || !digest.getAlgorithm().equals(algorithm)){
            digest = MessageDigest.getInstance(algorithm);
        }
        
        if ( encoder == null ){
            encoder = new BASE64Encoder();
        }
    }
    
    protected String encryptByAlgorithm(String algorithm, String value)throws NoSuchAlgorithmException {
        if (value == null) {
            throw new IllegalArgumentException("The value is null.");
        }

        useAlgorithm(algorithm);
        
        byte[] hash = digest.digest(value.getBytes());
        
        return encoder.encode(hash);
    }

}
